package edu.ipccenter.toster.ejb;

//import com.sun.xml.ws.api.tx.at.Transactional;
import java.util.Collection;
import edu.ipccenter.toster.Answer;
import edu.ipccenter.toster.Name;
import edu.ipccenter.toster.TestCase;
import edu.ipccenter.toster.jpa.AnswerID;
import edu.ipccenter.toster.jpa.JPAAnswer;
import edu.ipccenter.toster.jpa.JPATestCase;
import edu.ipccenter.toster.jpa.JPATheme;
import java.math.BigInteger;
import java.util.*;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateful(name = "TestCase")
//@Transactional
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class TestCaseBean implements TestCase {

    private JPATestCase testCase;
    private Collection<Name> themes = new ArrayList<Name>();
    private Collection<Answer> answers = new ArrayList<Answer>();
    @PersistenceContext(unitName = "TosterPU")
    private EntityManager em;

    public JPATestCase getTestCase() {
        if (testCase == null) {
            return null;
        }
        return testCase;
    }

    public void setTestCase(JPATestCase testCase) {
        this.testCase = testCase;
    }

    @Override
    public BigInteger getID() {
        if (testCase == null) {
            return null;
        }
        return testCase.getTcId();

    }

    @Override
    public void setID(BigInteger id) {
        if (testCase == null) {
            testCase = new JPATestCase();
        }
        this.testCase.setTcId(id);
    }

    @Override
    public String getName() {
        if (testCase == null) {
            return null;
        }
        return testCase.getTcName();
    }

    @Override
    public void setName(String name) {
        if (testCase == null) {
            testCase = new JPATestCase();
        }
        this.testCase.setTcName(name);
    }

    @Override
    public String getContent() {
        if (testCase == null) {
            return null;
        }
        return testCase.getTcContent();
    }

    @Override
    public void setContent(String content) {
        if (testCase == null) {
            testCase = new JPATestCase();
        }
        this.testCase.setTcContent(content);
    }

    @Override
    public String getDescription() {
        if (testCase == null) {
            return null;
        }
        return testCase.getDescription();

    }

    @Override
    public void setDescription(String description) {
        if (testCase == null) {
            testCase = new JPATestCase();
        }
        testCase.setDescription(description);
    }

    @Override
    public Collection<Name> getThemes() {

        if (testCase == null) {
            return null;
        }

        Set<JPATheme> tem = testCase.getThemes();
        themes.clear();
        Iterator iter = tem.iterator();

        while (iter.hasNext()) {
            JPATheme t = (JPATheme) iter.next();
            Name n = new Name();
            n.setID(t.getThemeId());
            n.setName(t.getThemeName());
            themes.add(n);
        }


        return themes;
    }

    @Override
    public Collection<Answer> getAnswers() {
        if (testCase == null) {
            return null;
        }
        //  System.out.println("Answers:"+testCase.getAnswers().size());
        Query q = em.createQuery("select c2 from JPAAnswer c2 where c2.tcId=:tcId");
        q.setParameter("tcId", getID());
        List<JPAAnswer> jans_list = q.getResultList();
        answers.clear();
        for (int i = 0; i < jans_list.size(); i++) {

            Answer ans = new Answer();

            ans.setID(jans_list.get(i).getTcId());
            ans.setAnsNum(jans_list.get(i).getAnsNum());
            ans.setContent(jans_list.get(i).getAnsContent());
            if (jans_list.get(i).getIscorrect() == 1) {
                ans.setCorrectness(true);
            } else {
                ans.setCorrectness(false);
            }

            answers.add(ans);
        }


        return answers;
    }

    /**
     * This method add <Answer> answer to the database
     */
    @Override
    public void addAnswer(Answer answer) {
        if (answer == null) {
            return;
        }
        try {
            //   System.out.println("Themas"+testCase.getThemes());
            AnswerID prKey = new AnswerID();
            prKey.setTcId(answer.getID());
            prKey.setAnsNum(answer.getAnsNum());

            JPAAnswer ans = new JPAAnswer();
            ans.setTcId(prKey.getTcId());
            ans.setAnsNum(prKey.getAnsNum());
            ans.setAnsContent(answer.getContent());

            if (answer.isCorrect()) {
                ans.setIscorrect(new Short("1"));
            } else {
                ans.setIscorrect(new Short("0"));
            }

            em.merge(ans);

        } catch (Exception ex) {
            System.out.println(ex.toString());
        }

    }

    @Override
    /**
     * This method removes <Answer> answer to the database
     */
    public void removeAnswer(Answer answer) {
        if (answer == null) {
            return;
        }
        try {
            AnswerID prKey = new AnswerID();
            prKey.setTcId(answer.getID());
            prKey.setAnsNum(answer.getAnsNum());

            JPAAnswer answ = em.find(JPAAnswer.class, prKey);

            if (answ != null) {
                em.remove(answ);
            }

        } catch (NullPointerException e) {
            System.out.println("Can't delete the element" + answer);
        }

    }

    @Override
    public void addTheme(BigInteger id) {//чтобы тема с данным id принадлежала этому testCase 

        if (id == null) {
            return;
        }
        try {
            Set<JPATheme> th = testCase.getThemes();
            //System.out.println("Themes:"+th);
            Query q = em.createQuery("select c from JPATheme c where c.themeId=:id");
            q.setParameter("id", id);
            JPATheme them = (JPATheme) q.getSingleResult();
            System.out.println("Thema:" + them.getThemeName());
            th.add(them);
            testCase.setThemes(th);
            em.merge(testCase);
        } catch (javax.persistence.NoResultException ex) {
            System.out.println("No such theme");
            return;
        }




    }

    @Override
    public void removeTheme(BigInteger id) {
        if (id == null) {
            return;
        }
        Set<JPATheme> th = testCase.getThemes();
        try {
            Query q = em.createQuery("select c from JPATheme c where c.themeId=:id");

            q.setParameter("id", id);
            JPATheme them = (JPATheme) q.getSingleResult();
            System.out.println("Thema:" + them.getThemeName());
            th.remove(them);
            testCase.setThemes(th);
            em.merge(testCase);
        } catch (javax.persistence.NoResultException ex) {
            System.out.println("No such theme");
            return;

        }



    }
}
